package com.jill.utils;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Component
public class AliyunOssOperator{

    private String endpoint = "https://oss-cn-beijing.aliyuncs.com";

    private String bucketName = "treenode-web-bucket";

    private String region = "cn-beijing";

    public String upload(byte[]content,String originalFilename) throws Exception {

        EnvironmentVariableCredentialsProvider credentialsProvider=CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        String dir=LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));

        String newFileName=dir+"/"+originalFilename;

        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, newFileName, new ByteArrayInputStream(content));

        ossClient.putObject(putObjectRequest);

        ossClient.shutdown();

        return endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+newFileName;//返回url
    }
}
